package com.wanmait.community.interceptor;

import com.auth0.jwt.exceptions.JWTVerificationException;
import com.wanmait.community.entity.Admin;
import com.wanmait.community.service.AdminService;
import com.wanmait.community.util.JWTUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class JWTInterceptor implements HandlerInterceptor {
    @Resource
    private AdminService adminService;
    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if("OPTIONS".equals(request.getMethod()) || "/admin/login".equals(request.getRequestURI())){
            return true;
        }
        String token = request.getHeader("token");
        if(token == null){
            throw new JWTVerificationException("token不能为空");
        }
//        Integer id = null;
//        try {
//            id = Integer.parseInt(JWTUtils.getAudience(token));
//        } catch (NumberFormatException e) {
//            throw new JWTVerificationException("token信息不正确");
//        }
//
//        //查询用户
//        Admin admin = adminService.findById(id);
//        if(admin == null){
//           throw new JWTVerificationException("根据token消息没有查询到用户");
//        }
        Admin admin =  (Admin) redisTemplate.opsForValue().get("token:"+token);
        if(admin == null){
           throw new JWTVerificationException("根据token消息没有查询到用户");
        }
        //获得token进行校验
        JWTUtils.verifyToken(token,admin.getAdminPass());
        request.setAttribute("admin",admin);

        return true;
    }

//    @Override
//    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
//    }
//
//    @Override
//    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
//    }
}
